/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.ServiceInstance;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.VirtualMachineInst;
import it.polimi.games.epkb.entityClasses.Service;
import it.polimi.games.epkb.entityClasses.Component;
import java.util.ArrayList;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class ServiceInstanceJpaController implements Serializable {

    public ServiceInstanceJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public ServiceInstanceJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(ServiceInstance serviceInstance) throws IllegalOrphanException, PreexistingEntityException, Exception {
        List<String> illegalOrphanMessages = null;
        Component componentOrphanCheck = serviceInstance.getComponent();
        if (componentOrphanCheck != null) {
            ServiceInstance oldServiceInstanceOfComponent = componentOrphanCheck.getServiceInstance();
            if (oldServiceInstanceOfComponent != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Component " + componentOrphanCheck + " already has an item of type ServiceInstance whose component column cannot be null. Please make another selection for the component field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            VirtualMachineInst idVMInstance = serviceInstance.getIdVMInstance();
            if (idVMInstance != null) {
                idVMInstance = em.getReference(idVMInstance.getClass(), idVMInstance.getId());
                serviceInstance.setIdVMInstance(idVMInstance);
            }
            Service idService = serviceInstance.getIdService();
            if (idService != null) {
                idService = em.getReference(idService.getClass(), idService.getId());
                serviceInstance.setIdService(idService);
            }
            Component component = serviceInstance.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                serviceInstance.setComponent(component);
            }
            em.persist(serviceInstance);
            if (idVMInstance != null) {
                idVMInstance.getServiceInstanceCollection().add(serviceInstance);
                idVMInstance = em.merge(idVMInstance);
            }
            if (idService != null) {
                idService.getServiceInstanceCollection().add(serviceInstance);
                idService = em.merge(idService);
            }
            if (component != null) {
                component.setServiceInstance(serviceInstance);
                component = em.merge(component);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findServiceInstance(serviceInstance.getId()) != null) {
                throw new PreexistingEntityException("ServiceInstance " + serviceInstance + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(ServiceInstance serviceInstance) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ServiceInstance persistentServiceInstance = em.find(ServiceInstance.class, serviceInstance.getId());
            VirtualMachineInst idVMInstanceOld = persistentServiceInstance.getIdVMInstance();
            VirtualMachineInst idVMInstanceNew = serviceInstance.getIdVMInstance();
            Service idServiceOld = persistentServiceInstance.getIdService();
            Service idServiceNew = serviceInstance.getIdService();
            Component componentOld = persistentServiceInstance.getComponent();
            Component componentNew = serviceInstance.getComponent();
            List<String> illegalOrphanMessages = null;
            if (componentNew != null && !componentNew.equals(componentOld)) {
                ServiceInstance oldServiceInstanceOfComponent = componentNew.getServiceInstance();
                if (oldServiceInstanceOfComponent != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Component " + componentNew + " already has an item of type ServiceInstance whose component column cannot be null. Please make another selection for the component field.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idVMInstanceNew != null) {
                idVMInstanceNew = em.getReference(idVMInstanceNew.getClass(), idVMInstanceNew.getId());
                serviceInstance.setIdVMInstance(idVMInstanceNew);
            }
            if (idServiceNew != null) {
                idServiceNew = em.getReference(idServiceNew.getClass(), idServiceNew.getId());
                serviceInstance.setIdService(idServiceNew);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                serviceInstance.setComponent(componentNew);
            }
            serviceInstance = em.merge(serviceInstance);
            if (idVMInstanceOld != null && !idVMInstanceOld.equals(idVMInstanceNew)) {
                idVMInstanceOld.getServiceInstanceCollection().remove(serviceInstance);
                idVMInstanceOld = em.merge(idVMInstanceOld);
            }
            if (idVMInstanceNew != null && !idVMInstanceNew.equals(idVMInstanceOld)) {
                idVMInstanceNew.getServiceInstanceCollection().add(serviceInstance);
                idVMInstanceNew = em.merge(idVMInstanceNew);
            }
            if (idServiceOld != null && !idServiceOld.equals(idServiceNew)) {
                idServiceOld.getServiceInstanceCollection().remove(serviceInstance);
                idServiceOld = em.merge(idServiceOld);
            }
            if (idServiceNew != null && !idServiceNew.equals(idServiceOld)) {
                idServiceNew.getServiceInstanceCollection().add(serviceInstance);
                idServiceNew = em.merge(idServiceNew);
            }
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.setServiceInstance(null);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.setServiceInstance(serviceInstance);
                componentNew = em.merge(componentNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = serviceInstance.getId();
                if (findServiceInstance(id) == null) {
                    throw new NonexistentEntityException("The serviceInstance with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ServiceInstance serviceInstance;
            try {
                serviceInstance = em.getReference(ServiceInstance.class, id);
                serviceInstance.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The serviceInstance with id " + id + " no longer exists.", enfe);
            }
            VirtualMachineInst idVMInstance = serviceInstance.getIdVMInstance();
            if (idVMInstance != null) {
                idVMInstance.getServiceInstanceCollection().remove(serviceInstance);
                idVMInstance = em.merge(idVMInstance);
            }
            Service idService = serviceInstance.getIdService();
            if (idService != null) {
                idService.getServiceInstanceCollection().remove(serviceInstance);
                idService = em.merge(idService);
            }
            Component component = serviceInstance.getComponent();
            if (component != null) {
                component.setServiceInstance(null);
                component = em.merge(component);
            }
            em.remove(serviceInstance);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<ServiceInstance> findServiceInstanceEntities() {
        return findServiceInstanceEntities(true, -1, -1);
    }

    public List<ServiceInstance> findServiceInstanceEntities(int maxResults, int firstResult) {
        return findServiceInstanceEntities(false, maxResults, firstResult);
    }

    private List<ServiceInstance> findServiceInstanceEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(ServiceInstance.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public ServiceInstance findServiceInstance(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(ServiceInstance.class, id);
        } finally {
            em.close();
        }
    }

    public int getServiceInstanceCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<ServiceInstance> rt = cq.from(ServiceInstance.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
